'use client'

import { useEffect, useState } from 'react'
import { VmsTopic, VmsCopy } from '@/types/Model'
import { useRouter, useSearchParams } from 'next/navigation'
import { Button } from '@/components/ui/button'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { DragDropContext, Droppable, Draggable, DroppableProvided, DroppableStateSnapshot } from '@hello-pangea/dnd'
import { toast } from '@/hooks/use-toast'

export default function ProgressPage() {
  const [topics, setTopics] = useState<VmsTopic[]>([])
  const [selectedTopic, setSelectedTopic] = useState<string>('')
  const [copies, setCopies] = useState<VmsCopy[]>([])
  const [loading, setLoading] = useState(true)
  const router = useRouter()
  // const searchParams = useSearchParams()

  const fetchTopics = async () => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch('/api/topic', {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })
      
      if (!response.ok) {
        if (response.status === 401) {
          router.push('/login')
          toast({
            title: '登录信息过期',
            description: '请重新登录',
            variant: 'destructive'
          })
          localStorage.clear()
          return
        }
      }
      
      const data = await response.json()
      setTopics(data)

      const params = new URLSearchParams(window.location.search)
      const topicId = params.get('topicid')
      // Check if there's a topicid in URL params
      // const topicId = searchParams.get('topicid')
      if (topicId) {
        // Validate if the topic exists
        const topicExists = data.some((t: VmsTopic) => t.id === topicId)
        if (topicExists) {
          setSelectedTopic(topicId)
          return
        }
      }

      // Default to first topic if no topicid in params
      if (data.length > 0) {
        setSelectedTopic(data[0].id)
      } else {
        setSelectedTopic('')
        setLoading(false)
      }
    } catch (error) {
      console.error('Error fetching topics:', error)
      toast({
        title: '数据获取失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  const fetchCopies = async (topicId: string) => {
    try {
      if (!topicId) return
      
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/copy?topic_id=${topicId}`, {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })
      
      if (!response.ok) throw new Error('Failed to fetch copies')
      
      const data = await response.json()
      setCopies(data)
    } catch (error) {
      console.error('Error fetching copies:', error)
      toast({
        title: '数据获取失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchTopics()
  }, [])

  useEffect(() => {
    if (selectedTopic) {
      fetchCopies(selectedTopic)
    } else {
      setCopies([])
    }
  }, [selectedTopic])

  const handleTopicChange = (value: string) => {
    setSelectedTopic(value)
  }

  const handleDragEnd = async (result: any) => {
      // 如果没有移动位置或者移动到无效位置，直接返回
      if (!result.destination) return
      
      // console.log(result.destination)
      // console.log(result.source)
      
      // 获取当前拖拽的对象
      // const draggedCopy = copies.find(copy => copy.id === result.draggableId);
      // console.log('当前拖拽的对象:', draggedCopy);
      
      // 保存原始列表用于回滚
      const originalCopies = [...copies]
      
      // 只更新拖拽对象的status
      const updatedCopies = copies.map(copy => {
        if (copy.id === result.draggableId) {
          return {
            ...copy,
            status: result.destination.droppableId
          }
        }
        return copy
      })

      // 先更新本地状态
      setCopies(updatedCopies)

    // 批量更新服务器数据
    try {
      const token = localStorage.getItem('token')
      const response = await fetch('/api/copy/batch', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(updatedCopies)
      })

      if (!response.ok) {
        throw new Error('Failed to update order')
      }
      toast({
        title: '更新成功',
        description: '文案状态和顺序已更新',
      })
    } catch (error) {
      console.error('Error updating order:', error)
      // 回滚到原始列表
      setCopies(originalCopies)
      toast({
        title: '排序更新失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  return (
    <div className="container mx-auto py-12 flex flex-col space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">项目进度</h1>
          <p className="text-muted-foreground">跟踪和管理项目文案进度</p>
        </div>
        <Select value={selectedTopic} onValueChange={handleTopicChange}>
          <SelectTrigger className="w-[340px]">
            <SelectValue placeholder={topics.length > 0 ? "选择项目" : "无可用项目"}>
              {topics.find(t => t.id === selectedTopic)?.name || "选择项目"}
            </SelectValue>
          </SelectTrigger>
          <SelectContent>
            {topics.length > 0 ? (
              topics.map(topic => (
                <SelectItem key={topic.id} value={topic.id}>
                  {topic.name}
                </SelectItem>
              ))
            ) : (
              <div className="text-sm text-muted-foreground px-2 py-1.5">
                无可用项目
              </div>
            )}
          </SelectContent>
        </Select>
      </div>

      {loading ? (
        <div className="flex justify-center items-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
        </div>
      ) : (
        <DragDropContext onDragEnd={handleDragEnd}>
          <div className="grid grid-cols-4 gap-4">
            {['文案编辑中', '脚本制作中', '拍摄中', '已完成'].map((statusValue) => (
              <Droppable key={statusValue} droppableId={statusValue}>
                {(provided: DroppableProvided, snapshot: DroppableStateSnapshot) => (
                  <div
                    {...provided.droppableProps}
                    ref={provided.innerRef}
                    className="bg-gray-50 p-4 rounded-lg"
                  >
                    <h3 className="font-semibold mb-4">{statusValue}</h3>
                    <div className="space-y-2">
                      {copies
                        .filter(copy => copy.status === statusValue)
                        .map((copy, index) => (
                          <Draggable key={copy.id} draggableId={copy.id} index={index}>
                            {(provided) => (
                              <div
                                ref={provided.innerRef}
                                {...provided.draggableProps}
                                {...provided.dragHandleProps}
                                className="p-3 border rounded-lg bg-white shadow-sm hover:shadow-md transition-shadow"
                              >
                                <div className="flex justify-between items-center">
                                  <div>
                                    <h4 
                                      className="font-medium hover:underline cursor-pointer"
                                      onClick={() => {
                                        if (copy.status === '文案编辑中') {
                                          window.open(`/copy/${copy.id}`, '_blank')
                                        } else if(copy.status === '脚本制作中','_blank') {
                                          window.open(`/scripts/${copy.id}`, '_blank')
                                        }else if(copy.status ==='拍摄中'){
                                          window.open(`/scripts/${copy.id}`, '_blank')
                                        }else {
                                          // router.push('/copy/review')
                                        }
                                      }}
                                    >
                                      {copy.title}
                                    </h4>
                                    <p className="text-sm text-muted-foreground">
                                      进度: {copy.finished_script_num}/{copy.script_num}
                                    </p>
                                  </div>
                                </div>
                              </div>
                            )}
                          </Draggable>
                        ))}
                      {provided.placeholder}
                      {copies.filter(copy => copy.status === statusValue).length === 0 && (
                        <div className="text-center text-muted-foreground py-4">
                          暂无文案
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </Droppable>
            ))}
          </div>
        </DragDropContext>
      )}
    </div>
  )
}
